package org.port.contacts;

import java.util.List;

import org.port.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactListAdapter extends ArrayAdapter<ContactEntry> {
	private final LayoutInflater mInflater;

	public ContactListAdapter(Context context) {
		super(context, R.layout.contacts_item);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// TODO Auto-generated constructor stub
	}

	public void setData(List<ContactEntry> data) {
		clear();
		if (data != null) {
			Log.d("FLOW", "Adapter data size: " + data.size());
			for (ContactEntry entry : data) {
				add(entry);
			}
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v;
		if (convertView == null) {
			v = mInflater.inflate(R.layout.contacts_item, parent, false);
		} else {
			v = convertView;
		}
		ContactEntry entry = getItem(position);
		Bitmap bm = null;
		try {
			Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, entry.mId
					+ "/photo");
			if (uri == null) {
				bm = BitmapFactory.decodeResource(getContext()
						.getResources(), R.drawable.sooji);
			} else {
				bm = Images.Media.getBitmap(getContext()
						.getContentResolver(), uri);
			}

			((ImageView) v.findViewById(R.id.imgbt_contacts_photo_small))
					.setImageBitmap(bm);
			((TextView) v.findViewById(R.id.txt_contacts_name))
					.setText(entry.mName);

		} catch (Exception e) {
			// TODO: handle exception
		}
		return v;
	}
}